﻿using System;
using System.Collections.Generic;
using System.Management;
using System.Data;
using JYH.Framework;
using System.Windows.Forms;
using System.IO;


namespace JYH.Framework
{
    public class Hardware
    {


        /// <summary>
        /// 认证方式定义
        /// C01:CPU信息 U02 USB盘 N03:MAC信息 B04:主板信息 H05:硬盘信息 M06:内存信息
        /// </summary>
        public static DataTable CheckType
        {
            get
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("CodeNO");
                dt.Columns.Add("CodeName");
                DataRow dr = dt.NewRow();
                dr["CodeNO"] = "C01";
                dr["CodeName"] = "CPU认证";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["CodeNO"] = "U02";
                dr["CodeName"] = "USB认证";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["CodeNO"] = "N03";
                dr["CodeName"] = "网卡认证";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["CodeNO"] = "B04";
                dr["CodeName"] = "主板认证";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["CodeNO"] = "H05";
                dr["CodeName"] = "硬盘认证";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["CodeNO"] = "M06";
                dr["CodeName"] = "内存认证";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["CodeNO"] = "";
                dr["CodeName"] = "请选择认证方式";
                dt.Rows.InsertAt(dr, 0);
                return dt;
            }
        }

        /// <summary>
        /// 获取CPU序列号代码
        /// </summary>
        /// <returns></returns>
        public static List<string> GetCpuID()
        {

            List<string> _serialNumber = new List<string>();
            try
            {
                //获取CPU序列号代码
                string cpuInfo = "";//cpu序列号
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                    string prex = "00";
                    string diskCode = cpuInfo;
                    diskCode=diskCode.Trim();
                    diskCode=diskCode.Replace(" ", "");
                    if (diskCode.Length < 30)
                    {

                        prex = diskCode.Length.ToString().PadLeft(2, '0');
                        diskCode =  prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                        diskCode= diskCode.Substring(0, 32).ToUpper();
                    }
                    else
                    {
                        diskCode = prex + diskCode;
                    }
                    _serialNumber.Add("C01" + diskCode);
                   // _serialNumber.Add(cpuInfo);
                }
                moc = null;
                mc = null;
                return _serialNumber;
            }
            catch
            {
                return null;
            }
            finally
            {
            }
        }

        /// <summary>
        /// 获取网卡硬件地址
        /// </summary>
        /// <returns></returns>
        public static List<string> GetMacAddress()
        {

            List<string> _serialNumber = new List<string>();
            try
            {
                //获取网卡硬件地址
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        mac = mo["MacAddress"].ToString();
                        string prex = "00";
                        string diskCode = mac;
                        diskCode = diskCode.Trim();
                        diskCode = diskCode.Replace(" ", "");
                        diskCode = diskCode.Replace(":", "");
                        if (diskCode.Length < 30)
                        {

                            prex = diskCode.Length.ToString().PadLeft(2, '0');
                            diskCode = prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                            diskCode = diskCode.Substring(0, 32).ToUpper();
                        }
                        else
                        {
                            diskCode = prex + diskCode;
                        }
                        _serialNumber.Add("N03"+diskCode);
                    }
                }
                moc = null;
                mc = null;
                return _serialNumber;
            }
            catch
            {
                return null;
            }
            finally
            {
            }

        }

        public static List<string> GetBIOSSerialNumber()
        {
            List<string> _serialNumber = new List<string>();
            try
            {
              ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_BIOS");
                string sBIOSSerialNumber = "";
                foreach (ManagementObject mo in searcher.Get())
                {
                    sBIOSSerialNumber = mo["SerialNumber"].ToString().Trim();

                    string prex = "00";
                    string diskCode = sBIOSSerialNumber;
                    diskCode=diskCode.Trim();
                    diskCode=diskCode.Replace(" ", "");
                    if (diskCode.Length < 30)
                    {

                        prex = diskCode.Length.ToString().PadLeft(2, '0');
                        diskCode = prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                        diskCode = diskCode.Substring(0, 32).ToUpper();
                    }
                    else
                    {
                        diskCode = prex + diskCode;
                    }
                    _serialNumber.Add("B04"+diskCode);
                   
                }
                return _serialNumber;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public static List<string> GetIPAddress()
        {

            List<string> _serialNumber = new List<string>();
            try
            {
                //获取IP地址
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        //st=mo["IpAddress"].ToString();
                        System.Array ar;
                        ar = (System.Array)(mo.Properties["IpAddress"].Value);
                        st = ar.GetValue(0).ToString();
                        string prex = "00";
                        string diskCode = st;
                        diskCode=diskCode.Trim();
                        diskCode=diskCode.Replace(" ", "");
                        if (diskCode.Length < 30)
                        {

                            prex = diskCode.Length.ToString().PadLeft(2, '0');
                            diskCode = prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                            diskCode = diskCode.Substring(0, 32).ToUpper();
                        }
                        else
                        {
                            diskCode = prex + diskCode;
                        }
                        _serialNumber.Add(diskCode);
                        //_serialNumber.Add(st);
                       
                    }
                }
                moc = null;
                mc = null;
                return _serialNumber;
            }
            catch
            {
                return null;
            }
            finally
            {
            }
        }

        /// <summary>
        /// 获取硬盘ID
        /// </summary>
        /// <returns></returns>
        public static List<string> GetDiskID()
        {

            List<string> _serialNumber = new List<string>();
            try
            {
                //获取硬盘ID
               // String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    string prex = "00";
                    string diskCode = (string)mo.Properties["Model"].Value;
                    diskCode= diskCode.Trim();
                    diskCode= diskCode.Replace(" ", "");
                    if (diskCode.Length <30)
                    {

                        prex = diskCode.Length.ToString().PadLeft(2, '0');
                        diskCode = prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                        diskCode = diskCode.Substring(0, 32).ToUpper();
                    }
                    else
                    {
                        diskCode = prex + diskCode;
                    }
                    _serialNumber.Add("H05"+diskCode);
                }
                moc = null;
                mc = null;
                return _serialNumber;
            }
            catch
            {
                return null;
            }
            finally
            {
            }

        }

        /// <summary>
        /// 操作系统的登录用户名
        /// </summary>
        /// <returns></returns>
        public static List<string> GetUserName()
        {
            List<string> _serialNumber = new List<string>();
            try
            {
               // string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    string prex = "00";
                    string diskCode = (string)mo["UserName"].ToString();
                    diskCode= diskCode.Trim();
                    diskCode= diskCode.Replace(" ", "");
                    if (diskCode.Length < 30)
                    {

                        prex = diskCode.Length.ToString().PadLeft(2, '0');
                        diskCode = prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                        diskCode = diskCode.Substring(0, 32).ToUpper();
                    }
                    else
                    {
                        diskCode = prex + diskCode;
                    }
                    _serialNumber.Add(diskCode);
                }
                moc = null;
                mc = null;
                return _serialNumber;
            }
            catch
            {
                return null;
            }
            finally
            {
            }

        }


        /// <summary>
        /// PC类型
        /// </summary>
        /// <returns></returns>
        public static List<string> GetSystemType()
        {

            List<string> _serialNumber = new List<string>();
            try
            {
               // string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    string prex = "00";
                    string diskCode = (string)mo["SystemType"].ToString();
                    diskCode= diskCode.Trim();
                    diskCode= diskCode.Replace(" ", "");
                    if (diskCode.Length < 30)
                    {

                        prex = diskCode.Length.ToString().PadLeft(2, '0');
                        diskCode = prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                        diskCode = diskCode.Substring(0, 32).ToUpper();
                    }
                    else
                    {
                        diskCode = prex + diskCode;
                    }
                    _serialNumber.Add(diskCode);
                   
                }
                moc = null;
                mc = null;
                return _serialNumber;
            }
            catch
            {
                return null;
            }
            finally
            {
            }

        }

        /// <summary>
        /// 物理内存
        /// </summary>
        /// <returns></returns>
        public static List<string> GetTotalPhysicalMemory()
        {
            List<string> _serialNumber = new List<string>();
            try
            {
               // string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    string prex = "00";
                    string diskCode = (string)mo["TotalPhysicalMemory"].ToString();
                    diskCode= diskCode.Trim();
                   diskCode= diskCode.Replace(" ", "");
                    if (diskCode.Length < 30)
                    {

                        prex = diskCode.Length.ToString().PadLeft(2, '0');
                        diskCode = prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                        diskCode = diskCode.Substring(0, 32).ToUpper();
                    }
                    else
                    {
                        diskCode = prex + diskCode;
                    }
                    _serialNumber.Add("M06"+diskCode);
                  
                }
                moc = null;
                mc = null;
                return _serialNumber;
            }
            catch
            {
                return null;
            }
            finally
            {
            }
        }

        /// <summary>
        /// 获取计算机名称
        /// </summary>
        /// <returns></returns>
        public static List<string> GetComputerName()
        {

            List<string> _serialNumber = new List<string>();
            try
            {
                string prex = "00";
                string diskCode = System.Environment.GetEnvironmentVariable("ComputerName");
                diskCode=diskCode.Trim();
                diskCode=diskCode.Replace(" ", "");
                if (diskCode.Length < 30)
                {

                    prex = diskCode.Length.ToString().PadLeft(2, '0');
                    diskCode = prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                    diskCode = diskCode.Substring(0, 32).ToUpper();
                }
                else
                {
                    diskCode = prex + diskCode;
                }
                _serialNumber.Add(diskCode);
               
                return _serialNumber;
            }
            catch
            {
                return null;
            }
            finally
            {
            }
        }

        /// <summary>
        /// 调用这个函数将本机所有U盘序列号存储到_serialNumber中
        /// </summary>
        public static  List<string> GetUSBInfo()
        {
            List<string> _serialNumber = new List<string>();
            string[] diskArray;
            string driveNumber;
            var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
            foreach (ManagementObject dm in searcher.Get())
            {
                getValueInQuotes(dm["Dependent"].ToString());
                diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(',');
                driveNumber = diskArray[0].Remove(0, 6).Trim();
                var disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
                foreach (ManagementObject disk in disks.Get())
                {
                    if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB")
                    {

                        string prex = "00";
                        string diskCode = parseSerialFromDeviceID(disk["PNPDeviceID"].ToString());
                        diskCode = diskCode.Trim();
                        diskCode = diskCode.Replace(" ", "");
                        if (diskCode.Length < 30)
                        {

                            prex = diskCode.Length.ToString().PadLeft(2, '0');
                            diskCode = prex + diskCode + Guid.NewGuid().ToString("N").ToUpper();
                            diskCode = diskCode.Substring(0, 32).ToUpper();
                        }
                        else
                        {
                            diskCode = prex + diskCode;
                        }
                        _serialNumber.Add("U02"+diskCode);
          
                    }
                }
            }
            return _serialNumber;
        }
        private static string parseSerialFromDeviceID(string deviceId)
        {
            var splitDeviceId = deviceId.Split('\\');
            var arrayLen = splitDeviceId.Length - 1;
            var serialArray = splitDeviceId[arrayLen].Split('&');
            var serial = serialArray[0];
            return serial;
        }

        private static string getValueInQuotes(string inValue)
        {
            var posFoundStart = inValue.IndexOf("\"");
            var posFoundEnd = inValue.IndexOf("\"", posFoundStart + 1);
            var parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1);
            return parsedValue;
        }


        public static string GetHardWareKey(string HWCode)
        {
            string Key = null;
            int len = 0;
            int.TryParse(HWCode.Substring(3, 2),out len);
            if (len == 0)
            {
                len = HWCode.Length - 5;
            }
            Key = HWCode.Substring(5, len);
            return Key;

        }
        /// <summary>
        /// 获取硬件信息
        /// </summary>
        /// <param name="CheckType">C01:CPU信息 U02 USB盘 N03:MAC信息 B04:主板信息 H05:硬盘信息 M06:内存信息 </param>
        /// <returns></returns>
        public static List<string> GetHardWare(string CheckType)
        {
            List<string> Code = new List<string>();
            switch (CheckType)
            {
                case "C01":
                    Code = JYH.Framework.Hardware.GetCpuID();
                    break;
                case "U02":
                    Code = JYH.Framework.Hardware.GetUSBInfo();
                    break;
                case "N03":
                    Code = JYH.Framework.Hardware.GetMacAddress();
                    break;
                case "B04":
                    Code = JYH.Framework.Hardware.GetBIOSSerialNumber();
                    break;
                case "H05":
                    Code = JYH.Framework.Hardware.GetDiskID();
                    break;
                case "M06":
                    Code = JYH.Framework.Hardware.GetTotalPhysicalMemory();
                    break;
                default:
                    Code = JYH.Framework.Hardware.GetCpuID();
                    break;

            }
            return Code;
        }

        public static bool CheckHardWare(string HwInfo)
        {
            bool result = false;
            if (string.IsNullOrEmpty(HwInfo))
            {
                return false;
            }
            if (HwInfo.Length < 5)
            {
                return false;
            }
            string checkType = HwInfo.Substring(0, 3);
            List<string> Code = new List<string>();
            Code = GetHardWare(checkType);
            foreach (string code in Code)
            {
                if (string.Equals(GetHardWareKey(HwInfo),GetHardWareKey(code)))
                {
                    return true;
                }
            }
            return result;
        }





    }
}
